package com.shawn.example.mvvmdemo.viewmodel

import android.util.Log
import androidx.lifecycle.*
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class SecondViewModel : ViewModel() {
    private val TAG = "SecondViewModel"
    private var flowLiveData: LiveData<Int> = MutableLiveData()
    val uiLiveData: LiveData<Int>
        get() = flowLiveData

    fun testFlow() {
        doLog("testFlow")
        val coldFlow = flow<Int> {
            for (i in 0..10) {
                doLog("$i")
                emit(i)
            }
        }
        viewModelScope.launch() {
            doLog("launch")
            flowLiveData = liveData {
                coldFlow
                    .onStart {
                        doLog("coldFlow onStart")
                    }
                    .catch {
                        doLog("coldFlow catch ")
                    }.onCompletion {
                        doLog("coldFlow onCompletion ")
                    }.flowOn(Dispatchers.IO)
//                    .conflate()
                    .collect {
                        delay(1000)
                        emit(it)
                    }
//                    .asLiveData()
            }



//                .asLiveData()
        }
    }

    private fun doLog(msg: String) {
        Log.d(TAG, "$msg, thread:${Thread.currentThread().name}")
    }
}